package cn.iocoder.yudao.module.def.controller.admin.projectprogress;

import cn.iocoder.yudao.module.def.dal.dataobject.project.ProjectDO;
import cn.iocoder.yudao.module.def.dal.mysql.project.ProjectMapper;
import cn.iocoder.yudao.module.def.service.project.ProjectService;
import cn.iocoder.yudao.module.def.utils.RoadNameProcessorUtil;
import cn.iocoder.yudao.module.system.controller.admin.user.vo.user.UserImportExcelVO;
import cn.iocoder.yudao.module.system.controller.admin.user.vo.user.UserImportRespVO;
import com.alibaba.excel.EasyExcel;
import io.swagger.v3.oas.annotations.Parameters;
import org.springframework.web.bind.annotation.*;

import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;


import java.net.URLEncoder;
import java.util.*;
import java.io.IOException;

import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.*;

import cn.iocoder.yudao.module.def.controller.admin.projectprogress.vo.*;
import cn.iocoder.yudao.module.def.dal.dataobject.projectprogress.ProjectProgressDO;
import cn.iocoder.yudao.module.def.service.projectprogress.ProjectProgressService;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

@Tag(name = "管理后台 - 工程进度")
@RestController
@RequestMapping("/def/project-progress")
@Validated
public class ProjectProgressController {

    @Resource
    private ProjectProgressService projectProgressService;

    @Resource
    private ProjectService projectService;

    @PostMapping("/create")
    @Operation(summary = "创建工程进度")
    @PreAuthorize("@ss.hasPermission('def:project-progress:create')")
    public CommonResult<Integer> createProjectProgress(@Valid @RequestBody ProjectProgressSaveReqVO createReqVO) {
        return success(projectProgressService.createProjectProgress(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新工程进度")
    @PreAuthorize("@ss.hasPermission('def:project-progress:update')")
    public CommonResult<Boolean> updateProjectProgress(@Valid @RequestBody ProjectProgressSaveReqVO updateReqVO) {
        projectProgressService.updateProjectProgress(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除工程进度")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('def:project-progress:delete')")
    public CommonResult<Boolean> deleteProjectProgress(@RequestParam("id") Integer id) {
        projectProgressService.deleteProjectProgress(id);
        return success(true);
    }

    @DeleteMapping("/deleteBatch")
    @Operation(summary = "批量删除工程进度")
    @Parameter(name = "ids", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('def:project:delete')")
    public CommonResult<Boolean> deleteBatch(@RequestParam("ids") List<Integer> ids) {
        projectProgressService.deleteBatch(ids);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得工程进度")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('def:project-progress:query')")
    public CommonResult<ProjectProgressRespVO> getProjectProgress(@RequestParam("id") Integer id) {
        ProjectProgressDO projectProgress = projectProgressService.getProjectProgress(id);
        return success(BeanUtils.toBean(projectProgress, ProjectProgressRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得工程进度分页")
    @PreAuthorize("@ss.hasPermission('def:project-progress:query')")
    public CommonResult<PageResult<ProjectProgressRespVO>> getProjectProgressPage(@Valid ProjectProgressPageReqVO pageReqVO) {
        PageResult<ProjectProgressDO> pageResult = projectProgressService.getProjectProgressPage(pageReqVO);
        PageResult<ProjectProgressRespVO> pageResultBean = BeanUtils.toBean(pageResult, ProjectProgressRespVO.class);
   /*     pageResultBean.getList().forEach(projectProgressRespVO -> {
            ProjectDO project = projectService.getProject(projectProgressRespVO.getProjectId());
            if (project != null){
                String actualFacilityName = project.getActualFacilityName();
                projectProgressRespVO.setActualFacilityName(RoadNameProcessorUtil.removeKilometerPart(actualFacilityName));
            }
        });*/
        return success(pageResultBean);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出工程进度 Excel")
    @PreAuthorize("@ss.hasPermission('def:project-progress:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportProjectProgressExcel(@Valid ProjectProgressPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<ProjectProgressDO> list = projectProgressService.getProjectProgressPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "工程进度.xls", "数据", ProjectProgressRespVO.class,
                        BeanUtils.toBean(list, ProjectProgressRespVO.class));
    }

    @PostMapping("/import")
    @Operation(summary = "导入")
    @Parameters({
            @Parameter(name = "file", description = "Excel 文件", required = true),
    })
    @PreAuthorize("@ss.hasPermission('system:user:import')")
    public CommonResult<ProjectProgressRespVO> importExcel(@RequestParam("file") MultipartFile file,
                                                      @RequestParam(value = "updateSupport", required = false, defaultValue = "false") Boolean updateSupport) throws Exception {
        List<ProjectProgressRespVO> list = ExcelUtils.read(file, ProjectProgressRespVO.class);
        return success(projectProgressService.importUserList(list, updateSupport));
    }

    @GetMapping("/export-statistics")
    public void exportStatistics(HttpServletResponse response) throws IOException {
        List<ProjectStatisticsExport> data = projectProgressService.getAnnualStatistics();

        String fileName = URLEncoder.encode("项目年度统计", "UTF-8");

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        EasyExcel.write(response.getOutputStream(), ProjectStatisticsExport.class)
                .sheet("项目年度统计")
                .doWrite(data);
    }

}